package com.simple.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.simple.entity.SysUserLog;
import com.simple.repository.SysUserLogRespository;
import com.simple.service.SysUserLogService;
import com.simple.utils.SysConfig;

@Service
public class SysUserLogServiceImpl implements SysUserLogService{
	
	@Autowired
	SysUserLogRespository  sysUserLogRespository;

	@Override
	public void saveAndFlush(SysUserLog sysUserLog) {
		
		sysUserLogRespository.saveAndFlush(sysUserLog);
	}

	@Override
	public List<SysUserLog> findByUser(String username) {
		// TODO Auto-generated method stub
		return sysUserLogRespository.findByUser(username);
	}

	@Override
	public Page<SysUserLog> findAll(Integer page,Integer limit) {
		if(null==limit) {
			limit=10;
		}
		Sort sort=Sort.by(Sort.Direction.DESC, "createDate");
		Pageable pageable=PageRequest.of(page-1,limit,sort);
		Specification<SysUserLog> specification=new Specification<SysUserLog>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<SysUserLog> root, CriteriaQuery<?> query,CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<>(1);
				list.add(criteriaBuilder.equal(root.get("username"),SysConfig.getUsername()));
				Predicate[] predicate = new Predicate[list.size()];
				
				return criteriaBuilder.and(list.toArray(predicate));
			}
		};
		return sysUserLogRespository.findAll(specification, pageable);
	}

}
